import { RouteRecordRaw, RouterView } from 'vue-router'
import { defineStore } from 'pinia'
import { getUserMenuApi } from '@/api/user'
import { markRaw } from 'vue'
import Layout from '@/layout/index.vue'

const modules = import.meta.glob('/src/views/**/**.vue') // 匹配菜单路由
// 获取组件地址
function getComponent(componentName: string) {
  let component: Component = null
  switch (componentName) {
    case 'Layout':
      component = markRaw(Layout)
      break
    case 'RouterView':
      component = markRaw(RouterView)
      break
    default:
      component = modules[`/src/views${componentName}.vue`]
      break
  }
  return component
}

// 将接口数据转为RouteRecordRaw类型数据
function treeToRouter(list): RouteRecordRaw[] {
  const sortList = list.sort((a, b) => a.sort - b.sort)
  return sortList.map(item => {
    return {
      meta: {
        icon: item.icon,
        title: item.title
      },
      path: item.path,
      name: item.name,
      component: getComponent(item.file_path),
      children: item.children ? treeToRouter(item.children) : []
    }
  })
}
// 动态路由菜单
export const useMenuStore = defineStore('menu', {
  state: (): { menuList: RouteRecordRaw[] } => ({
    menuList: []
  }),
  getters: {
    getMenuList: state => state.menuList
  },
  actions: {
    async setMenuList() {
      try {
        const { code, data } = await getUserMenuApi()
        if (code === 0) {
          this.menuList = treeToRouter(data)
        }
      } catch (e) {
        console.log(e)
      }
    }
  }
})
